package com.control;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import com.model.Buffer;
import com.model.Node;
import com.view.optionpanel.ShowMessage;

public class BufferControl {
	private static int maxBufferNum = 5;
	private List<Buffer> buffers = new ArrayList<Buffer>();
	private static final BufferControl bufferControl = new BufferControl();

	public static BufferControl getInstance() {
		return bufferControl;
	}

	public boolean addBuffer(Buffer buffer) {
		System.out.println("zheshi" + buffers.size());
		if (buffers.size() < maxBufferNum) {
			buffers.add(buffer);
			return true;
		} else {
			ShowMessage.error("内存已满", null);
			return false;
		}
	}

	public void removeBuffer(Buffer buffer) {
		buffers.remove(buffer);
	}

	public List<Buffer> getBuffers() {

		return this.buffers;
	}

	public Buffer newBuffer(String path, String OType, Node<String> node, int a) throws FileNotFoundException {
		
		List<Buffer> buffers=BufferControl.getInstance().getBuffers();
		Buffer buffer = new Buffer();
		int i=buffers.size();
		for(int j=0;j<i;j++){
			Buffer y=buffers.get(j);
			if(y.getPath().equals(path)){
				if(y.getOType().equals(OType)){
					buffers.remove(y);
					break;
				}
				else {
					ShowMessage.error("该文件已以其他形式打开，请在已打开文件表中关闭再打开！", null);
					buffer.setPath("0000");
					return buffer;
				}
			}
		}
		
		buffer.setPath(path);
		buffer.setFileType(PublicControl.getFileType(node.getData().toString()));
		buffer.setStart(node.getStart());
		buffer.setOType(OType);

		int size = 0;
		InputStream f1 = new FileInputStream("resources/" + node.getMyself() + ".txt");
		try {
			size = f1.available();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		try {
			f1.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		buffer.setFileLength(size);

		int read = node.getStart(), write = node.getStart();
		if (OType.equals("读")) {
			int b = a / 64 ;
			read = node.getStart() + b;
		} else if (OType.equals("写")) {
			int b = a / 64 ;
			write = node.getStart() + b;
		}

		buffer.setReadPoint(read);
		buffer.setWritePoint(write);

		return buffer;
	}

}
